<?php

namespace App\Services;


use App\Models\ArticleCategory;
use DB;

class ArticleCategoryService
{

    /**
     * 获取全部文章分类数据
     * @return \Illuminate\Database\Eloquent\Collection|\App\Models\ArticleCategory[]
     */
    public function getAllArticleCategories()
    {
        return ArticleCategory::all();
    }

    /**
     * 根据分类名称查询记录数
     * @param $name
     * @return int
     */
    public function getCountByArticleCategoryName($name)
    {
        return ArticleCategory::where('name', $name)->count('id');
    }

    /**
     * 保存文章分类信息
     * @param $attr
     * @return \App\Models\ArticleCategory
     */
    public function saveArticleCategory($attr)
    {
        return ArticleCategory::create($attr);
    }

    /**
     * 获取文章分类的树形结构数组
     * @return array
     */
    public function getTreeArticleCategory()
    {
        return ArticleCategory::getTreeArray($this->getAllArticleCategories());
    }

    /**
     * 根据Id查询文章分类
     * @param $id
     * @return \App\Models\ArticleCategory
     */
    public function getArticleCategoryById($id)
    {
        return ArticleCategory::find($id);
    }

    /**
     * 根据给定Id查询所有的子分类Id
     * @param $id
     * @return array
     */
    public function getAllSubIds($id)
    {
        return ArticleCategory::getAllChildrenIds($id);
    }

    /**
     * 根据Id更新文章分类
     * @param $id
     * @param $attr
     * @return bool|int
     */
    public function updateArticleCategoryById($id, $attr)
    {
        $articleCategory = $this->getArticleCategoryById($id);
        return $articleCategory->update($attr);
    }

    /**
     * 根据Id删除文章分类，同时删除其子分类
     * @param $id
     */
    public function deleteArticleCategoryById($id)
    {
        $arr = ArticleCategory::getAllChildrenIds($id);
        DB::transaction(function () use ($arr, $id) {
            if (!empty($arr)) {
                ArticleCategory::destroy($arr);
            }
            return ArticleCategory::destroy($id);
        });
    }

}